import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

const MethodChannel channel = MethodChannel('ohos.flutter.picker/photoviewpicker');

// 获取缩略图
Future<String> getThumbnail(id) async {
  return await channel.invokeMethod(
    'getThumbnail',
    {'assetId': id},
  );
}

// 获取媒体文件
Future<String> getFullImage(id) async {
  return await channel.invokeMethod(
    'getFullImage',
    {'assetId': id},
  );
}

// 获取媒体文件
Future<num> getPhotoType(id) async {
  return await channel.invokeMethod(
    'getPhotoType',
    {'assetId': id},
  );
}

class PhotoPickerPage extends StatelessWidget {
  const PhotoPickerPage({super.key});

  @override
  Widget build(BuildContext context) {
    return PhotoPicker(
      title: 'Photo Picker',
    );
  }
}

class PhotoPicker extends StatefulWidget {
  const PhotoPicker({super.key, required this.title});

  final String title;

  @override
  State<PhotoPicker> createState() => _PhotoPickerState();
}

class _PhotoPickerState extends State<PhotoPicker> {
  Future<Map<Object?, Object?>>? _loadAllPhoto;
  List<Widget> widgetList = <Widget>[];
  List<String> pathList = <String>[];
  final List<String> select = <String>[]; // 选中的图片id

  bool isFullImage = false; // 是否选择原图
  bool isFullViwe = false; // 是否大图
  String? id;

  @override
  void initState() {
    super.initState();
    print("initState====>");
    this.getAllImage();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {});
    });
  }

  void getAllImage() async {
    var result = await channel.invokeMethod(
      'getAllImage',
      {},
    );
    setState(() {
      _loadAllPhoto = new Future(() => result);
    });
  }

  Future<Widget> buildThumbnail(id) async {
    var path = await getThumbnail(id);
    return ImageView(id, path, (value) {
      if (value) {
        this.select.add(id);
      } else {
        this.select.remove(id);
      }
      print("是否选中：$value");
    }, (id) {
      print('放大$id');

      setState(() {
        this.id = id;
        isFullViwe = true;
      });
    });
  }

  // 返回选中图片路径
  void getResult() async {
    var result = new Map<String, String>();
    for (var i = 0; i < this.select.length; i++) {
      var id = this.select.elementAt(i);
      var path = this.isFullImage ? await getFullImage(id) : await getThumbnail(id);
      result[id] = path;
    }
    Navigator.pop(context, result);
  }

  Widget _buildGridView(BuildContext context, AsyncSnapshot<Map<Object?, Object?>> snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasData) {
        try {
          final Map combined = snapshot.data!;
          combined.forEach((key, value) async {
            if(!pathList.contains(value)) {
              pathList.add(value);
              Widget widget = await buildThumbnail(value);
              widgetList.add(widget);
            }
          });
        }catch(error) {
          print("发生错误：$error");
        }
      }
    }
    return Expanded(
      child: GridView(
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
        ),
        children: [...widgetList],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return isFullViwe
        ? LargeView(this.id!, () {
            setState(() {
              this.isFullViwe = false;
            });
          })
        : Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
              centerTitle: true,
            ),
            body: Center(
              child: Column(
                children: <Widget>[
                  FutureBuilder<Map<Object?, Object?>>(
                    future: _loadAllPhoto,
                    builder: _buildGridView,
                  ),
                  Column(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: ElevatedButton(
                          child: const Text('完成'),
                          onPressed: () {
                            this.getResult();
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
  }
}

class ImageView extends StatefulWidget {
  final String path;
  final String id;
  final ValueChanged<bool> changed;
  final ValueChanged<String> onTap;
  ImageView(this.id, this.path, this.changed, this.onTap, {super.key});

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  bool selected = false;
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        GestureDetector(
          onTap: () {
            widget.onTap(widget.id);
          },
          child: Image.file(
            File(widget.path),
            fit: BoxFit.cover,
            filterQuality: FilterQuality.high,
            width: 100,
            height: 100,
          ),
        ),
        Positioned(
          right: 10,
          top: 10,
          child: Container(
            // color: Colors.orange,
            height: 20,
            width: 20,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  selected = !selected;
                  widget.changed(selected);
                });
              },
              child: selected ? Image.asset('assets/images/selected.png') : Image.asset('assets/images/unselected.png'),
            ),
          ),
        ),
      ],
    );
  }
}

class LargeView extends StatefulWidget {
  final String id;
  final VoidCallback back;
  const LargeView(this.id, this.back, {super.key});

  @override
  State<LargeView> createState() => _LargeViewState();
}

class _LargeViewState extends State<LargeView> {
  num photoType = 1;
  String? path;
  @override
  void initState() {

    getType().then((value) => {
      setState(() {
        photoType = value;
      })
    });

    getPath().then((value) {
      setState(() {
        path = value;
      });
    });
    print('$path');
    super.initState();
  }

  Future<num> getType() async{
    var a =  await getPhotoType(widget.id);
    return a;
  }

  Future<String> getPath() async {
    return await getFullImage(widget.id);
  }

  @override
  Widget build(BuildContext context) {
    return path != null
        ? SafeArea(
            child: Column(children: [
              Container(
                height: 50,
                color: Colors.orange,
                child: Row(
                  children: [
                    GestureDetector(
                        child: Icon(Icons.backpack_outlined),
                        onTap: () {
                          // widget.onTap(widget.id);
                          print('点击手势');
                          widget.back();
                        })
                  ],
                ),
              ),
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    // widget.onTap(widget.id);
                    print('点击手势');
                  },
                  child: photoType == 1? Image.file(
                    File(path!),
                    fit: BoxFit.contain,
                    filterQuality: FilterQuality.high,
                  ):Text('这是视频'),
                ),
              ),
              Container(
                height: 50,
                color: Colors.orange,
              ),
            ]),
          )
        : Container();
  }
}
